const { verifyToken } = require('../utils/index');
const unlessPath = require('../config/default').unless_path;

// 不需要验证的接口
function unless(url) {
  return unlessPath.findIndex(item => url.match(item)) !== -1;
}

// 自定义接口授权
module.exports.auth = async (ctx, next) => {
  console.log('当前访问路径：' + ctx.request.path);
  if (unless(ctx.request.path)) return await next();
  let token = ctx.request.header['authorization'];
  if (!token) return ctx.sendResult(null, 401, 'access denied');
  const decode = verifyToken(token);
  if (typeof decode == 'object') {
    if (ctx.request.body['username'] == decode['user_name']) {
      return await next();
    } else {
      ctx.sendResult(null, 400, 'invalid token');
    }
  } else {
    ctx.sendResult(null, 400, decode);
  }
};
